<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Order extends MY_Controller {

	function buy_now(){
		$post_data = $this->input->post();
		$this->load->model('Order_model');
		// print_r($post_data);exit;
		$settle_id = $this->Order_model->buy_now($this->user_data['id'],$post_data['course_id'],$post_data['num']);
		if($settle_id>0){
			header("Location:/order/settle/{$settle_id}");exit;
		}
	}
	/**
	 * 结算预览页面
	 *
	 */
	public function settle($id)
	{
	if( $this->logged_in==0) {header("Location:/");exit;}
		$post_data = $this->input->post();
		$this->load->model('Order_model');
		//查询结算信息
		$settle = $this->Order_model->get_settle_by_id($id);

		$course_type = $settle['order_type'];
		if($course_type == 1){
			$this->check_school_video_user_code();
		}
		if(empty($settle)) {header("Location:/");exit;}

		if($course_type == 5){
			$shopping_cart = get_field_by_where("shopping_cart", "*", "cart_id='{$settle['cart_ids']}'");
			$shixun_data = json_decode(file_get_contents("http://123.206.137.187:804/HandlerData.ashx?action=GetZhangtaoInfo"),true);
			$shixun_info = array();
			if(!empty($shixun_data['rows']) && count($shixun_data['rows']) > 0){
				foreach ($shixun_data['rows'] as $key => $value) {
					if($value['Id'] == $shopping_cart['course_id']){
						$shixun_info = $value;
					}
				}
			}
			if(empty($shixun_info)){
				show_error_message("/shixun", "实训不存在");exit;
			}
		}
		
		
		if($post_data){
			$has_err = 0;
			//判断学员信息是否完善
			if($course_type == 3){
				$this->load->model('Student_model');
				$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
				if(empty($student)){
					$this->smarty->assign("error", "请填写学员信息");
					$has_err = 1;
				}
			}
			if($has_err == 0){
				$this->load->model('Order_model');
				if($course_type == 4){
					$order_id = $this->Order_model->submit_subject_order($post_data['settle_id']);
				}elseif($course_type == 5){
					$order_id = $this->Order_model->submit_shixun_order($post_data['settle_id'],$shixun_info['ztName'], 'http://admin.520dax.com'.$shixun_info['titleImage']);
				}else{
					$order_id = $this->Order_model->submit_order($post_data['settle_id'],$course_type);	
				}
				
				if($order_id>0){
				  header("Location:/order/pay/{$order_id}");exit;
				}
			}
		}
		
		


		//查询购物车信息
		$cart_list = $this->Order_model->get_cart_info_by_settle($id, $course_type);
		if($course_type == 5){
			$cart_list[0]['title'] = $shixun_info['ztName'];
			$cart_list[0]['course_img'] = 'http://admin.520dax.com'.$shixun_info['titleImage'];
		}
		if(empty($cart_list)){header("Location:/");exit;}
		// print_r($cart_list);exit;
		$this->smarty->assign("cart_list", $cart_list);
		//计算总价
		$total_amout = 0.0;
		foreach ($cart_list as $cart) {
			if($cart['school_id'] == 0){
				$total_amout += $cart['fx_price'] * $cart['quantity'];
			}else{
				$total_amout += $cart['price'] * $cart['quantity'];
			}
		}
		$this->smarty->assign("total_amout", $total_amout);

		//获取学员信息
		$this->load->model('Student_model');
		$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
		$this->smarty->assign("student", $student);
		$this->smarty->assign("course_type", $course_type);
		$this->smarty->assign("settle_id", $id);
		$this->smarty->display("order/settle.html");
	}

	/**
	 * 设置学员信息
	 * @param  string $value [description]
	 * @return [type]        [description]
	 */
	public function student_info()
	{
		// $settle_id = $this->input->get('settle_id');
		// $this->smarty->assign("settle_id", $settle_id);
		$post_data = $this->input->post();

		if($post_data){
			$this->load->model('Student_model');
			$result = $this->Student_model->add_student_info($this->user_data['id'],$post_data);
			if($result>0){
				print_r('{"result":"0","msg":"success"}');exit;
				// $this->smarty->display("order/student_info_success.html");
				// exit;
		}
		}
		$this->load->model('Student_model');
		$student = $this->Student_model->get_student_by_userid($this->user_data['id']);
		$this->smarty->assign("student", $student);
		$this->smarty->display("order/student_info.html");

	}



  /**
  **  订单支付
  */
  function pay($order_id){
  	
	$this->load->model('Order_model');
	$order = $this->Order_model->get_order_by_id($order_id);
	if(empty($order)){
		header("Location:/");exit;
	}
	if($this->logged_in==0){
		header("Location:/login");exit;
	}
	if($order['order_type'] == 1){
		$this->check_school_video_user_code();
	}
	// print_r($this->user_data['id']);exit;
	if($order['buyer_user_id']!=$this->user_data['id']){
		print_r("不是你的订单");
		exit;
	}
	$this->smarty->assign("order", $order);
	//查询学校信息
	$this->load->model('School_model');
	$school = $this->School_model->get_school_by_id($this->school_id);

	
	$this->smarty->assign("school", $school);

	$this->smarty->display("order/pay.html");
  }

	/**
	 * 支付成功跳转
	 * @param  [type] $order_id [description]
	 * @return [type]           [description]
	 */
	public function success($order_id)
	{
		
		$this->load->model('Order_model');
		$order = $this->Order_model->get_order_by_id($order_id);
		if(empty($order)){
			header("Location:/");exit;
		}
		if($this->logged_in==0){
			header("Location:/login");exit;
		}

		if($order['buyer_user_id']!=$this->user_data['id']){
			print_r("不是你的订单");
			exit;
		}

		//修改订单支付状态
		$this->Order_model->order_pay_success($order_id);

		$this->smarty->assign("order", $order);

		$this->smarty->display("order/success.html");
	}


	public function wx_query_order()
	{	
		$post_data = $this->input->post();
		$order_id = $post_data['order_id'];

		$this->load->model('Order_model');
		$order = $this->Order_model->get_order_by_id($order_id);
		if(empty($order)){
			header("Location:/");exit;
		}
		if($this->logged_in==0){
			header("Location:/logreg");exit;
		}
		if($order['order_type'] == 1){
			$this->check_school_video_user_code();
		}
		// print_r($this->user_data['id']);exit;
		if($order['buyer_user_id']!=$this->user_data['id']){
			show_error_message("/user/orders", "不是你的订单");
			exit;
		}

		require_once 'third_party/wxpayApi/wxpay.php';
		$wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$this->school_id}'");
		if(!$wx_config_data || empty($wx_config_data['app_id']) || empty($wx_config_data['mch_id']) || empty($wx_config_data['apikey']) || empty($wx_config_data['apiclient_cert']) || empty($wx_config_data['apiclient_key'])){
			show_error_message("/user/orders", "该学校不支持微信支付");
		}
		$wx_config['appid'] = $wx_config_data['app_id'];
		$wx_config['mch_id'] = $wx_config_data['mch_id'];
		$wx_config['apikey'] = $wx_config_data['apikey'];
		$wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
		$wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
		$wx_config['notify_url'] = $this->config->item("wx_pay_notify_url");
		$products = json_decode($order['order_products'],true);
		$products_id = '';
		$products_name = '';
		$price = 0;
		foreach ($products as $key => $value) {
			if($key != 0){
				$products_id .= ',' . $value['id'];
				$products_name .= "、" . $value['title'];
			}else{
				$products_id .= $value['id'];
				$products_name .= $value['title'];
			}
			// $price += $value['price'];
		}
		$price = $order['payment_money_amount'];
		$weixin_pay = new wxpay($wx_config);
		$param['body']             = "德安信订单-".$products_name;
		$param['attach']           = $order['order_id'];
		$param['detail']           = '德安信订单，单号：' . $order['order_id'];
		$param['out_trade_no']     = $order['order_id'];
		$param['total_fee']        = $price * 100;
		$param["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];
		$param["time_start"]       = date("YmdHis");
		$param["time_expire"]      = date("YmdHis", time() + 29000);
		$param["notify_url"]       = $wx_config['notify_url'];
		$param["trade_type"]       = "NATIVE"; //扫码支付模式二
		$param["product_id"]       = $products_id;
		$response = $weixin_pay->unifiedOrder($param);
		if(!$response || $response['return_code'] == 'FAIL'){
			show_error("微信统一下单失败，" . $response['return_msg']);exit;
		}

		$result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'code_url' => '');
		if ($response['return_code'] == 'SUCCESS') {
			if ($response['result_code'] == 'SUCCESS') {
				$result['status']   = 0;
				$result['code_url'] = $response["code_url"];
				/*$log_info = $this->db->select('id')->where(array('order_id' => $order['order_id'], 'status' => 5))->get('o2o_school_pay_logs')->row_array();
				if (empty($log_info)) {
					//记录订单操作数据库日志
					$order_log['pay_type']   = 1;
					$order_log['order_id']     = $order['order_id'];
					$order_log['order_detail'] = json_encode($order);
					$order_log['status']       = 5; //5、等待付款
					// $order_log['add_time']     = time();
					$this->db->insert("o2o_school_pay_logs", $order_log);
				}*/
			} else {
				$result['status']   = 2;
				$result['msg_code'] = $response["err_code"];
				$result['msg_des']  = $response["err_code_des"];
			}
		} else {
			$result['status']   = 1;
			$result['msg_code'] = '微信服务器通信错误';
			$result['msg_des']  = $response["return_msg"];
		}

		$this->smarty->assign("seo", $param['body']);
		$this->smarty->assign("result", $result);
		$this->smarty->assign("order_data", $order);
		$this->smarty->display("order/weixinpay.html");
	}

	public function wx_create_pay_qrcode()
	{
		require_once "third_party/wxpayApi/phpqrcode/phpqrcode.php";
		$url = urldecode(trim($this->input->get('data', true)));
		QRcode::png($url);
	}

	function check_order_status(){
		$order_no = trim($this->input->post('order_no', true));

		require_once 'third_party/wxpayApi/wxpay.php';

		$wx_config_data = get_field_by_where("o2o_school_wx_config", "*", "school_id='{$this->school_id}'");
		if(!$wx_config_data || empty($wx_config_data['app_id']) || empty($wx_config_data['mch_id']) || empty($wx_config_data['apikey']) || empty($wx_config_data['apiclient_cert']) || empty($wx_config_data['apiclient_key'])){
			show_error_message("/user/orders", "该学校不支持微信支付");
		}
		$wx_config['appid'] = $wx_config_data['app_id'];
		$wx_config['mch_id'] = $wx_config_data['mch_id'];
		$wx_config['apikey'] = $wx_config_data['apikey'];
		$wx_config['sslcertPath'] = $wx_config_data['apiclient_cert'];
		$wx_config['sslkeyPath'] = $wx_config_data['apiclient_key'];
		$weixin_pay = new wxpay($wx_config);
		$response = $weixin_pay->orderQuery('', $order_no);
		$result = array('status' => -1, 'msg_code' => '', 'msg_des' => '', 'order' => '');
		if ($response['return_code'] == 'SUCCESS') {
			if ($response['result_code'] == 'SUCCESS' && $response['trade_state'] == 'SUCCESS') {
				/*$user_commission = get_field_by_where("user_commission", "*", "order_id='{$order_no}' AND status = 0");
				if($user_commission){
					$this->db->where("id", $user_commission['user_id']);
					$this->db->set("integral", "integral + {$user_commission['commission']}", false);
					$this->db->set("commission_total", "commission_total + {$user_commission['commission']}", false);
					$this->db->update("user_account");
				}*/
				//佣金
				$this->load->model("User_model");
	        	$user_commission = $this->User_model->get_user_commission($order_no);
	        	if(count($user_commission > 0)){
	        		foreach ($user_commission as $key => $value) {
	        			$this->db->where("user_id", $value['user_id']);
						$this->db->set("balance", "balance + {$value['commission']}", false);
						$this->db->set("commission_total", "commission_total + {$value['commission']}", false);
						$this->db->update("user_account");
						if($this->db->affected_rows() > 0){
							$this->db->where("id", $value['id']);
							$this->db->update("user_commission", array("status" => 1));
						}
	        		}
	        	}

				$order_info = get_field_by_where("shopping_orders", "*", "order_id = '{$order_no}'");

				//扣网校视频课激活码
				/*if($order_info['order_type'] == 1){
					$time = time();
					$today_time = strtotime(date('Y-d-m'));
		        	$sql = "UPDATE {$this->db->dbprefix}o2o_school_video_user_codes SET status = 2, use_uid='{$order_info['buyer_user_id']}', use_time='{$time}', order_id='{$order_no}' WHERE school_id = '{$order_info['school_id']}' AND status = 1 AND expire_time >= '{$today_time}' ORDER BY id ASC LIMIT 1";
		        	$this->db->query($sql);
		        	if($this->db->affected_rows() > 0){
		        		$this->db->where("id", $order_info['school_id']);
						$this->db->set("item_num", "item_num - 1", false);
						$this->db->update("o2o_school");
		        	}
	        	}*/

				// if(1==1){
				if($order_info['order_status'] != 1 && $order_info['order_status'] != 2){
					$order_data['payment_method']  = 1;	//支付方式（1：微信支付，2：支付宝）
					$order_data['payment_status']  = 2; //支付状态：0未支付1支付中2支付成功3支付失败
					$order_data['payment_time']    = strtotime($response['time_end']); //付款时间
					$order_data['payment_on']      = $response['transaction_id']; //第三方支付交易号
					$order_data['payment_money_amount']     = $response['total_fee'] / 100; //实付金额
					$order_data['buyer_account']   = $response['openid']; //微信openid
					$order_data['order_detail']    = json_encode($response);
					$order_data['order_status']    = 1;	//订单确认成功，订单扣除激活码
					$this->db->update('shopping_orders', $order_data, array('order_id' => $order_no));

					$order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");
					if($order_item){
						if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
							$push_jihuo_code = false;
							if($order_info['order_type'] == 2 || $order_info['order_type'] == 3){
								$use_status = 1;
								$push_jihuo_code = true;
							}else{
								$course_info = get_field_by_where("course", "school_id", "id='{$order_item['course_id']}'");
								if($course_info['school_id'] > 0){
									$use_status = 1;
									$push_jihuo_code = true;
								}else{
									$use_status = $this->deduct_code($order_info, $order_item);
								}
							}
							if($push_jihuo_code){
								$time = time();
								$use_code_data['course_id'] = $order_item['course_id'];
								$use_code_data['course_type'] = $order_info['order_type'];
								$use_code_data['user_id'] = $order_info['buyer_user_id'];
								$use_code_data['code'] = 'schoo_course';
								$use_code_data['order_num'] = $order_info['order_num'];
								$use_code_data['school_id'] = $order_info['school_id'];
								$use_code_data['add_time'] = $time;
								$use_code_data['effective_time'] = $order_item['effective_time'];
								$this->db->insert("o2o_student_course", $use_code_data);
							}
						}elseif($order_info['order_type'] == 4){
							$subject_info = get_field_by_where("b_subject", "school_id", "id='{$order_item['course_id']}'");
							if($subject_info['school_id'] > 0){
								$use_status = 1;
								$push_jihuo_code = true;
							}else{
								$use_status = $this->deduct_code($order_info, $order_item);
							}
						}elseif($order_info['order_type'] == 5){
							$use_status = $this->deduct_code($order_info, $order_item);
						}

						if($use_status == 1){
							$this->db->update('shopping_orders', array('order_status' => 2), array('order_id' => $order_no));	//成功扣除激活码
							//插入有效期表的数据,先查询是否存在有效期数据,如果有就更新，没有就插入
							$time = time();
							$where = "data_type='{$order_info['order_type']}' AND data_id='{$order_item['course_id']}' AND uid='{$order_info['buyer_user_id']}'";
							$terms_info = get_field_by_where("o2o_student_item_terms", "*", $where);
							$terms_data['school_id'] = $order_info['school_id'];
							$terms_data['data_type'] = $order_info['order_type'];
							$terms_data['data_id'] = $order_item['course_id'];
							$terms_data['uid'] = $order_info['buyer_user_id'];
							$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $time;
							$terms_data['last_order_id'] = $order_no;
							if($terms_info){
								if($terms_info['lose_time'] > $time){
									$terms_data['lose_time'] = 3600 * 24 * $order_item['effective_time'] + $terms_info['lose_time'];
								}
								$this->db->where("id", $terms_info['id']);
								$this->db->update("o2o_student_item_terms", $terms_data);
							}else{
								$this->db->insert("o2o_student_item_terms", $terms_data);
							}
						}
					}
				}
				$result['status'] = 0;
				$result['order']  = $response;
			} else {
				$result['status']   = 2;
				$result['msg_code'] = !empty($response["err_code"]) ? $response["err_code"] : 0;
				$result['msg_des']  = !empty($response["err_code_des"]) ? $response["err_code_des"] : '';
			}
		} else {
			$result['status']   = 1;
			$result['msg_code'] = '微信服务器通信错误';
			$result['msg_des']  = $response["return_msg"];
		}

		exit(json_encode($result));
	}

	function deduct_code($order_info, $order_item){
		$use_status = 0;
		if(!empty($order_info['order_id'])){
			$time = time();
			// $order_item = get_field_by_where("shopping_order_item", "*", "order_id='{$order_info['order_id']}'");
			if($order_item){
				$use_code_data = array();
				$where = "school_id = '{$order_info['school_id']}' AND status = 1 ";
				if($order_info['order_type'] > 0 && $order_info['order_type'] < 4){
					//课程订单
					$where .= "AND course_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_video_course_codes", "*", $where . " ORDER BY id ASC");
					if($code_info){
						//插入课程激活码使用记录
						$use_code_data['course_id'] = $order_item['course_id'];
						$use_code_data['course_type'] = $order_info['order_type'];
						$use_code_data['user_id'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['add_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_course", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改实训激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['user_id'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_video_course_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}elseif($order_info['order_type'] ==  4){
					//题库订单、获取题库激活码
					$where .= "AND subject_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_topic_codes", "*", $where . " ORDER BY id ASC");

					if($code_info){
						//插入题库激活码使用记录
						$use_code_data['subject_id'] = $order_item['course_id'];
						$use_code_data['uid'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['use_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_system_topics", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改题库激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_topic_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}elseif($order_info['order_type'] == 5){
					//实训订单、获取题库激活码
					$where .= "AND sx_id = '{$order_item['course_id']}'";
					$code_info = get_field_by_where("o2o_school_system_shixun_codes", "*", $where . " ORDER BY id ASC");

					if($code_info){
						//插入实训激活码使用记录
						$use_code_data['sx_id'] = $order_item['course_id'];
						$use_code_data['uid'] = $order_info['buyer_user_id'];
						$use_code_data['code'] = $code_info['code'];
						$use_code_data['order_num'] = $order_info['order_num'];
						$use_code_data['school_id'] = $order_info['school_id'];
						$use_code_data['use_time'] = $time;
						$use_code_data['effective_time'] = $order_item['effective_time'];
						$this->db->insert("o2o_student_system_shixun", $use_code_data);
						if($this->db->insert_id() > 0){
							//修改实训激活码的使用状态
							$code_update_data = array("status" => 2, "use_uid" => $use_code_data['uid'], "use_time" => $time);
							$this->db->where("id", $code_info['id']);
							$this->db->update("o2o_school_system_shixun_codes", $code_update_data);
							$use_status = 1;
						}
					}
				}
			}
		}
		return $use_status;
	}

	function pay_success($order_id){
		if(empty($order_id)){
			show_error_message("/", "非法操作");
			exit;
		}
		$order_info = get_field_by_where("shopping_orders", "order_type", "order_id='{$order_id}'");
		if($order_id){
			switch ($order_info['order_type']) {
				case 1:
					show_message("/user/orders", "支付成功");
				break;

				case 2:
					show_message("/user/orders_zhibo", "支付成功");
				break;

				case 3:
					show_message("/user/orders_banke", "支付成功");
				break;

				case 4:
					show_message("/user/orders_tiku", "支付成功");
				break;

				case 5:
				show_message("/user/orders_shixun", "支付成功");
				break;
			}
		}else{
			show_error_message("/", "非法操作");
		}
	}

	function buy($subject_id, $type){
		$this->load->model('Order_model');
		$settle_id = $this->Order_model->buy_now($this->user_data['id'],$subject_id,1,$type);
		if($settle_id>0){
			header("Location:/order/settle/{$settle_id}");exit;
		}else{
			header("Location:/");exit;
		}
	}

	function check_school_video_user_code(){
		$time = strtotime(date('Y-m-d'));
		$code_info = get_field_by_where("o2o_school_video_user_codes", "*", "school_id = '{$this->school_id}' AND status = 1 AND expire_time >= '{$time}'");
		if(!$code_info){
			show_error_message("/video", "该学校未开通视频课购买，请联系客服");
		}
	}
}
